package com.ifonly.activerecord.sql.handlers;

import com.ifonly.activerecord.sql.ResultSetHandler;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-28 13:14
 * @since JDK 1.6
 */
public class ScalarResultSetHandler<T> extends ResultSetHandler<T> {
    private String column;
    private int index;

    public ScalarResultSetHandler(String column) {
        this(column, -1);
    }

    public ScalarResultSetHandler(int index) {
        this(null, index);
    }

    public ScalarResultSetHandler(String column, int index) {
        this.column = column;
        this.index = index;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T handle(ResultSet rs) throws SQLException {
        if (rs.next()) {
            if (this.column == null) {
                return (T) rs.getObject(this.index);
            }
            return (T) rs.getObject(this.column);
        }
        return null;
    }

}
